﻿using ZquenceStudio3Host.DspPlugins.Synthesizers.Nodesizer.Engine;

namespace DefaultDspPlugins.Common.Modulizer.Engine.Modules.Analog
{
    [ModuleDisplay("Capacitor")]
    public class CapacitorModule : BaseModule
    {
        public readonly ModuleInput In;
        public readonly ModuleOutput Out;

        public readonly InputModuleParameter CapacitorFarad;

        private double mLastCapacitorValue;

        public CapacitorModule(ModuleManager manager)
            : base(manager)
        {
            // Add input and outputs to module.
            AddInput(In = new ModuleInput("In", IOType.AudioOrWaveform, this));

            CapacitorFarad = new InputModuleParameter(this, "F", 0, IOType.Audio);
            CapacitorFarad.Label = "Farad";
            CapacitorFarad.MinValue = 0.00001;
            CapacitorFarad.MaxValue = 1;
            AddModuleParameter(CapacitorFarad);

            AddOutput(Out = new ModuleOutput("Out", IOType.AudioOrWaveform, this));
        }

        public override void Process()
        {
            if (In.IsConnected)
            {
                for (int i = 0; i < Out.AudioBuffer.Length; i++)
                {
                    double valueIn = In.FromOutput.AudioBuffer[i];
                    mLastCapacitorValue = System.Math.Min(mLastCapacitorValue, Out.AudioBuffer[i]);

                    double farad = CapacitorFarad.Values[i] * 0.01;

                    if (valueIn > mLastCapacitorValue)
                    {
                        mLastCapacitorValue += farad * valueIn * 1000;
                    }
                    else
                    {
                        mLastCapacitorValue -= farad;
                    }

                    mLastCapacitorValue = System.Math.Min(1.0, System.Math.Max(0.0, mLastCapacitorValue));

                    Out.AudioBuffer[i] = mLastCapacitorValue;
                }
            }
        }
    }
}
